﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Security.Principal;
using System.Web;
using System.Web.Caching;


namespace BusinessLogic.Security
{
    public static class AuthenticationService
    {
        /// <summary>
        /// Аутентификация
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>        
        /// <returns>1-ok, 2-заблокирован, 0 - не верный логин/пароль</returns>
        public static int AuthenticateUser(string userName, string password)
        {
            return UserPrincipal.AuthenticateUser(userName, password);
        }

        private static string GetPrincipalChacheKey(string userName)
        {
            return "current_user_principal_" + userName;
        }

        public static IPrincipal AuthorizeUser(string userName)
        {
            //if (HttpContext.Current.Cache[GetPrincipalChacheKey(userName)] == null)
            //{
            var principal = UserPrincipal.LoginToApplication(HttpContext.Current.User.Identity.Name);
            if (principal != null)
                HttpContext.Current.Cache.Insert(GetPrincipalChacheKey(userName), principal, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration);
            return principal;
            //}
            //else
            //    return (IPrincipal)HttpContext.Current.Cache[GetPrincipalChacheKey(userName)];

        }

        /// <summary>
        /// Выход
        /// </summary>
        public static void SingOut()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.Session != null)
                {
                    HttpContext.Current.Cache.Remove(GetPrincipalChacheKey(HttpContext.Current.User.Identity.Name));
                    HttpContext.Current.Session.Remove(GetPrincipalChacheKey(HttpContext.Current.User.Identity.Name));
                    //HttpContext.Current.Session.RemoveAll();
                    //HttpContext.Current.Session.Timeout = 1;
                }
                FormsAuthentication.SignOut();
                HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl, true);
            }
        }

    }
}
